package jmotor.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * Component:Utility
 * Description:Stream utilities
 * Date: 11-8-16
 *
 * @author Andy.Ai
 */
public class StreamUtils {
    private StreamUtils() {
    }

    public static byte[] transform(InputStream inputStream) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            int data;
            while ((data = inputStream.read()) != -1) {
                os.write(data);
            }
            return os.toByteArray();
        } finally {
            inputStream.close();
            os.close();
        }
    }

    public static InputStream transform(String str, String charset) throws UnsupportedEncodingException {
        return new ByteArrayInputStream(str.getBytes(charset));
    }

    public static InputStream transform(String str) {
        return new ByteArrayInputStream(str.getBytes());
    }

    public static InputStream getStream4ClassPath(String name) {
        return ClassUtils.getClassLoader().getResourceAsStream(name);
    }

    public static Properties loadProperties(InputStream inputStream) throws IOException {
        try {
            Properties properties = new Properties();
            properties.load(inputStream);
            return properties;
        } finally {
            inputStream.close();
        }
    }
}
